<template>
  <div>
    <el-dialog
      :title="isEdit? '编辑部门': '添加部门'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="true"
    >
      <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
            <el-option v-for="obj in employeeList" :key="obj.id" :value="obj.username" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="enterFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmpoyeeSimpleAPI, addDepartmentsAPI, getDepartDetailAPI, updateDepartmentsAPI } from '@/api'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    parentId: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean
    },
    originList: {
      type: Array,
      default: _ => [],
      required: true
    }

  },
  data() {
    const valiCode = (rule, value, callback) => {
      let existCodeList = this.originList.map(item => item.code)

      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error('编码' + value + '已存在')) : callback()
    }

    const validateName = (rules, value, callback) => {
      let arr = this.originList.filter(item => item.pid === this.targetId).map(item => item.name)
      if (this.isEdit) {
        const obj = this.originList.find(item => item.id === this.targetId)
        const pid = obj.pid
        arr = this.originList.filter(item => item.id === pid && item.id !== this.targetId).map(item => item.name)
      }
      arr.includes(value) ? callback(new Error(`此部门名字${value}已存在`)) : callback()
    }

    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employeeList: [],
      targetId: '',
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: true }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: valiCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    isEdit() {
      this.getCompanyDetaiFn()
    }
  },

  created() {
    this.getEmpoyeeFn()
  },
  methods: {
    async getEmpoyeeFn() {
      const res = await getEmpoyeeSimpleAPI()
      console.log(res)
      this.employeeList = res.data
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.$emit('update:dialogVisible', false)
        })
        .catch(_ => {})
    },
    // 取消按钮
    cancelFn() {
      // this.isEdit = false
      this.$emit('update:dialogVisible', false)
    },
    // 确认按钮
    async enterFn() {
      this.$refs.deptForm.validate(async(valid) => {
        if (valid) {
          if (this.isEdit === true) {
            console.log(valid)
            const res = await updateDepartmentsAPI({
              ...this.form,
              pid: this.parentId
            })
            this.$message.success(res.message)
          } else {
            const res = await addDepartmentsAPI({
              ...this.form, pid: this.parentId
            })
            if (!res.success) return this.$message.error(res.message)
            this.$message.success(res.message)
          }

          this.$emit('update:dialogVisible', false)
          this.$emit('resetList')
        }
      })
    },
    async getCompanyDetaiFn() {
      if (this.isEdit === true) {
        const res = await getDepartDetailAPI(this.parentId)
        this.form = res.data
        console.log(this.parentId)
        console.log(res, 'edit', this.form)
      } else {
        this.form = {
          name: '', // 部门名称
          code: '', // 部门编码
          manager: '', // 部门管理者
          introduce: '' // 部门介绍
        }
      }
    }

  }
}
</script>

<style>

</style>
